<template>
  <div id="rightTop">
    <a-input v-model:value="title" placeholder="请输入文章标题" />
    <a-button style="margin-left: 10px" @click="save">保存草稿</a-button>
    <a-button style="margin-left: 10px" @click="publish">发布</a-button>
  </div>
  <a-textarea
    v-model:value="intr"
    placeholder="请输入文章简介(默认为正文前80个字)"
    showCount
    :maxlength="80"
  />
  <div ref="editor"></div>
</template>
<script>
import { defineComponent, ref, onMounted, onBeforeUnmount } from "vue";
import WangEditor from "wangeditor";
import VueEvent from "../../utils/event";
import { doArticle, openArticle } from "../../api/create";
import { message } from "ant-design-vue";
import { formatTime } from "../../utils/date";

export default defineComponent({
  setup() {
    const aid = ref("");
    const title = ref("");
    const editor = ref();
    const intr = ref("");

    const save = () => {
      if (intr.value == "") {
        intr.value = instance.txt.text().substring(0, 79) + "……";
      }
      doArticle({
        url: "/create/doArticle",
        aid: aid.value,
        title: title.value,
        intr: intr.value,
        content: instance.txt.html(),
        success: (res) => {
          // console.log(res.data);
          message.info(res.data);
          location.reload();
        },
        err: (err) => {
          console.log(err);
        },
      });
    };
    const publish = () => {
      if (intr.value == "") {
        intr.value = instance.txt.text().substring(0, 50);
      }
      let dateNow = formatTime();
      openArticle({
        url: "/create/openArticle",
        aid: aid.value,
        addTime: dateNow,
        title: title.value,
        intr: intr.value,
        content: instance.txt.html(),
        success: (res) => {
          // console.log(res.data);
          message.info(res.data);
          location.reload();
        },
        err: (err) => {
          console.log(err);
        },
      });
    };

    VueEvent.on("AsBody", (e) => {
      // console.log(e);
      aid.value = e.aid;
      title.value = e.AsTitle;
      intr.value = e.intr;
      instance.txt.html(e.content);
    });

    let instance;
    onMounted(() => {
      instance = new WangEditor(editor.value);
      Object.assign(instance.config, {
        onchange() {
          instance.config.uploadImgParams = { aid: aid.value };
          // console.log(aid.value);
        },
      });
      instance.config.height = 500;
      instance.config.zIndex = 500;
      instance.config.uploadImgServer =
        "http://localhost:3000/create/imgArticle";
      instance.config.uploadFileName = "PicturesOfAs";
      instance.create();
    });

    onBeforeUnmount(() => {
      instance.destroy();
      instance = null;
    });

    return {
      editor,
      title,
      save,
      publish,
      aid,
      intr,
    };
  },

  components: {},
});
</script>
        
<style scoped>
#rightTop {
  width: 100%;
  display: flex;
  margin-bottom: 10px;
}
</style>
